#encoding:utf-8
# import sys
# reload(sys)
# sys.setdefaultencoding('utf-8')

from common.models import Address, Area
from companies.models import Company, Vacancy, VacancyStatus
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response, redirect, get_object_or_404
from django.template import RequestContext
from common.forms import AdressForm
from countries_states.models import *
from companies.forms import VacancyForm
from django.utils.translation import ugettext as _
from datetime import date, timedelta

@login_required
def index_db_company(request):
    # vacancies = Vacancy.objects.filter(company_id=request.user.company.pk, status__in=[1, 3])
    return render_to_response('dashboard/index_db_company.html',
                              {'isIndexDbComp': True, 'user': request.user},
                              context_instance = RequestContext(request))

@login_required
def deactivate_vacancy(request, vacancy_id):
    vacancy = get_object_or_404(Vacancy, pk=vacancy_id, company=request.user.company.pk)
    messages.success(request, _(u'Hemos eliminado la vacante exitosamente'))
    vacancy.status=VacancyStatus.objects.get(codename__exact='removed') #Inactiva
    vacancy.save()
    return redirect('companies_index_db_company')
    # vacancies = Vacancy.objects.filter(company_id=request.user.company.pk, status__in=[1, 3])
    # return render_to_response('dashboard/index_db_company.html', {'isIndexDbComp': True, 'dashboard_company': True, 'user': request.user, 'vacancies':vacancies}, context_instance = RequestContext(request))

@login_required
def republish_vacancy(request, vacancy_id):
    vacancy = get_object_or_404(Vacancy, pk=vacancy_id, company=request.user.company.pk)
    messages.success(request, _(u'Hemos publicado nuevamente la vacante exitosamente'))
    vacancy.status=VacancyStatus.objects.get(codename__exact='active') #Activa
    vacancy.save()
    return redirect('companies_index_db_company')

@login_required
def show_vacancies(request, codename_status='active'):
    status = get_object_or_404(VacancyStatus, codename=codename_status)
    vacancies = Vacancy.objects.filter(company_id=request.user.company.pk, status=status)
    return render_to_response('dashboard/vacancies/show_vacancies.html',
                              {'isIndexDbComp': True, 'status': status,
                               'vacancies': vacancies},
                              context_instance = RequestContext(request))

@login_required
def add_vacancy(request):
    if request.method == 'POST':
        try:
            if int(request.POST['state']) == 0:
                state_selected = 0
            else:
                state_selected = State.objects.get(id=request.POST['state'])
        except:
            state_selected = None
        try:
            if int(request.POST['area']) <= 0:
                area_selected = None
            else:
                area_selected = Area.objects.get(id=request.POST['area'])
        except:
            area_selected = None
        form = VacancyForm(data=request.POST, files=request.FILES, state_selected=state_selected, area_selected=area_selected)
        if form.is_valid():
            user = request.user
            company = Company.objects.get(user_id=user.pk)
            new_vacancy = form.save(company=company, user=user)
            if new_vacancy.status.codename == 'active':
                messages.success(request, _(u'Se ha publicado la vacante exitosamente'))
            elif new_vacancy.status.codename == 'programed':
                # TODO: Investigar como mostrar la fecha en español
                # expiration_date = new_vacancy.pub_date+timedelta(30)
                messages.success(request, _(u'Hemos registrado su vacante y se activará a partir del día %s y vence el %s')
                                          % (new_vacancy.pub_date.strftime('%d %B %Y'), new_vacancy.end_date.strftime('%d %B %Y')))
            # form.save()
            return redirect('companies_index_db_company')
    else:
        form = VacancyForm()
    return render_to_response('dashboard/vacancies/add_vacancy.html',
                              {'isAddVacancy': True,
                               'form': form,
                               'user': request.user},
                              context_instance = RequestContext(request))

@login_required
def update_vacancy(request, vacancy_id):
    vacancy = get_object_or_404(Vacancy, pk=vacancy_id, company=request.user.company.pk)
    company = Company.objects.get(user_id=request.user.pk)
    if request.method == 'POST':
        try:
            if int(request.POST['state']) == 0:
                state_selected = 0
            else:
                state_selected = State.objects.get(id=request.POST['state'])
        except:
            state_selected = None
        try:
            if int(request.POST['area']) <= 0:
                area_selected = None
            else:
                area_selected = Area.objects.get(id=request.POST['area'])
        except:
            area_selected = None
        form = VacancyForm(data=request.POST, files=request.FILES, state_selected=state_selected, area_selected=area_selected)
        if form.is_valid():
            vacancy = form.update(vacancy)
            messages.success(request, _(u'Hemos modificado la vacante exitosamente'))
            return redirect('companies_index_db_company')
    else:
        form = VacancyForm(instance=vacancy, vacancy= vacancy, state_selected=vacancy.state, area_selected=vacancy.area, change_vacancy=True)
    return render_to_response('dashboard/vacancies/add_vacancy.html',
                              {'isAddVacancy': True,
                               'form': form,
                               'user': request.user},
                              context_instance = RequestContext(request))